package com.jeesit.cloud.spot.web.api_controller.contract_pending_order;

import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.spot.service.IContractPendingOrderService;
import com.jeesit.cloud.verify.UserAuthDetail;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.util.ExportExcel;
import com.jeesit.cloud.dto.ContractPendingOrderDto;
import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesit.cloud.model.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeesit.cloud.dto.JSONResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *   相关接口
 *　　
 *   @description ContractPendingOrder 接口
 *   ---------------------------------
 *   @author lss
 *   @date 2024-01-15
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/contract_pending_order")
@Api(tags = {"合同点价信息表"})
public class ContractPendingOrderController {

    @Autowired
    private IContractPendingOrderService contractPendingOrderService;

    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    @PostMapping(value = "/contract_pending_order_page")
    public JSONResult<Page<ContractPendingOrder>> getContractPendingOrderPage(Authentication authentication,@Validated(QueryAction.class)ContractPendingOrderDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<ContractPendingOrder> page=new Page<ContractPendingOrder>(dto.getPageNo(), dto.getPageSize());
        contractPendingOrderService.page(page,dto);
        JSONResult<Page<ContractPendingOrder>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping(value = "/contract_pending_order_list")
    public JSONResult<ContractPendingOrder> getContractPendingOrderList(Authentication authentication, @Validated(QueryAction.class)ContractPendingOrderDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<ContractPendingOrder> list = contractPendingOrderService.list(dto.getSize(),dto);
        JSONResult<ContractPendingOrder> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('ContractPendingOrder_Export','SUPER_ADMIN')")
    @PostMapping(value = "/contract_pending_order_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)ContractPendingOrderDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<ContractPendingOrder> datas = contractPendingOrderService.list(0,dto);
        String[] header = new String[]{"","点价合约","点价期限","创建时间","合同id","对方姓名","对方联系方式","对方联系人id","我方姓名","我方联系方式","我方联系人id","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(ContractPendingOrder it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getUuid());
            data.add(it.getInstrumentUuid());
            data.add(Optional.ofNullable(it.getDeadline()).map(s->sdf.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getContractUuid());
            data.add(it.getAdvName());
            data.add(it.getAdvPhone());
            data.add(it.getAdvLinkmanUuid());
            data.add(it.getName());
            data.add(it.getPhone());
            data.add(it.getLinkmanUuid());
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('ContractPendingOrder_Add','SUPER_ADMIN')")
    @ModuleLog("ContractPendingOrder")
    @PostMapping("/contract_pending_order_add")
    public JSONResult<ContractPendingOrder> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) ContractPendingOrderDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<ContractPendingOrder> res= saveData(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('ContractPendingOrder_Modify','SUPER_ADMIN')")
    @ModuleLog("ContractPendingOrder")
    @PostMapping("/contract_pending_order_edit")
    public JSONResult<ContractPendingOrder> saveEditEntity(HttpServletRequest request,Authentication authentication,@Validated(UpdateAction.class) ContractPendingOrderDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<ContractPendingOrder> res= saveData(user,entity.getUuid(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    private JSONResult<ContractPendingOrder> saveData(User user,Long id,ContractPendingOrderDto entity){
        JSONResult<ContractPendingOrder> res = new JSONResult<>();
        ContractPendingOrder it = new ContractPendingOrder();
        if(id==null){
            it.setDeleted(false);
        } else {
            it = contractPendingOrderService.getById(entity.getUuid());
        }
        it.setInstrumentUuid(entity.getInstrumentUuid());
        it.setDeadline(entity.getDeadline());
        it.setContractUuid(entity.getContractUuid());
        it.setAdvName(entity.getAdvName());
        it.setAdvPhone(entity.getAdvPhone());
        it.setAdvLinkmanUuid(entity.getAdvLinkmanUuid());
        it.setName(entity.getName());
        it.setPhone(entity.getPhone());
        it.setLinkmanUuid(entity.getLinkmanUuid());
        contractPendingOrderService.saveOrUpdate(it);
        res.setData(it);
        res.setSuccess(true);
        res.setMessage("保存成功");
        return res;
    }


    /**
     * @description 删除
     *
     * @author lss
     * @date 2024-01-15
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('ContractPendingOrder_Remove','SUPER_ADMIN')")
    @ModuleLog("ContractPendingOrder")
    @PostMapping("contract_pending_order_del")
        public JSONResult<Void> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        for(int i=0;i<ids.length;i++){
            ContractPendingOrder it = contractPendingOrderService.getById(ids[i]);
            contractPendingOrderService.removeById(it.getUuid());
        }
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
        res.setMessage("删除成功");
        res.setSuccess(true);
        return res;
    }

}

